package com.tuanbiao.presenter;

import com.hzjq.data.entity.ACapEntity;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.controllers.SingleCheckController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.utils.MediaUtils;

import java.util.List;

import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/19 16:40
 */
public class SingleCheckPresenter extends BasePresenter<SingleCheckController.Model, SingleCheckController.View> implements SingleCheckController.Presenter {
    private int mPageIndex = 1;

    public SingleCheckPresenter(SingleCheckController.Model model, SingleCheckController.View rootView) {
        super(model, rootView);
    }


    @Override
    public void refresh() {
        mPageIndex = 1;
        getCheckedDetonators(mPageIndex);
    }

    @Override
    public void loadMore() {
        mPageIndex++;
        getCheckedDetonators(mPageIndex);
    }

    @Override
    public void singleCheck() {
        mModel.singleDetonatorCheck(new OnBaseResultCallback<ACapEntity>() {
            @Override
            public void onSuccess(ACapEntity entity) {
                Timber.i("singleCheck#" + entity);
                if (null != entity && entity.getError() == -9) {
                    MediaUtils.playSound(R.raw.code_error);
                    mRootView.showNoteDialog("编码规则不符合");
                } else {
                    refresh();
                }
            }

            @Override
            public void onFailed(String msg) {
                mRootView.showNoteDialog(msg);
            }
        });
    }

    @Override
    public void deleteCheck(ACapEntity aCapEntity) {
        mModel.deleteSingleDetonators(aCapEntity, unused -> {
            mRootView.showMessage("删除成功");
            mRootView.onDetonatorDelete(aCapEntity);
            refresh();
        });
    }

    @Override
    public void clearCheck() {
        mModel.clearSingleDetonators(unused -> {
            mRootView.showMessage("清除成功");
            refresh();
        });
    }

    private void getCheckedDetonators(int pageIndex) {
        mModel.querySingleDetonators(pageIndex, new OnBaseResultCallback<List<ACapEntity>>() {
            @Override
            public void onSuccess(List<ACapEntity> entities) {
                if (mPageIndex == 1) mRootView.setItems(entities);
                else mRootView.addItems(entities);
            }

            @Override
            public void onFailed(String msg) {
                mRootView.showMessage(msg);
            }
        });
    }
}
